package com.neo.agent.connection;

import com.neo.push.core.AcceptPush;
import com.neo.push.core.SafetyPushText;
import com.neo.push.core.connection.ConnectionMonitor;
import com.neo.push.core.connection.SocketConnection;
import com.neo.push.server.message.PushMessageFactory;
import com.neo.push.server.message.PushMessageMonitor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by lock on 17-8-1.
 */
@Controller
public class PushController {


    private ConnectionMonitor connectionMonitor;
    private ConnectionService connectionService;
    private PushMessageMonitor pushMessageMonitor;
    private Logger logger = LoggerFactory.getLogger(PushController.class);


    @RequestMapping(value = "/push",method = RequestMethod.POST)
    public @ResponseBody void pushText(@RequestParam String target, @RequestParam String text) throws Exception{
        String connectionId = connectionService.findConnectionId(target);
        AcceptPush pushText = PushMessageFactory.instancePushWithoutId(target,text);
        pushMessageMonitor.messageSend(pushText);
        if(null!=connectionId){
            SocketConnection connection = connectionMonitor.findConnection(connectionId);
            if(null!=connection){
                connection.writeMessage(new SafetyPushText(pushText));
            }
        }else{
            logger.info(" connection :"+target+" nof found !");
        }
    }

    @Autowired
    public void setPushMessageMonitor(PushMessageMonitor pushMessageMonitor) {
        this.pushMessageMonitor = pushMessageMonitor;
    }

    @Autowired
    public void setConnectionService(ConnectionService connectionService) {
        this.connectionService = connectionService;
    }

    @Qualifier("mongoConnectionMonitor")
    @Autowired
    public void setConnectionMonitor(ConnectionMonitor connectionMonitor) {
        this.connectionMonitor = connectionMonitor;
    }
}
